/* -*- mode: C; c-basic-offset: 8 -*-
 *
 * shuffle.c - print random permutation of argv
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#ifdef DEVRANDOM
#include <fcntl.h>
#endif

void
seed()
{
	int i, j;
#ifdef DEVRANDOM
	int fd;
#endif
	i = getpid();
	j = time(NULL) ^ (i + (i << 15)); /* Thank you the Camel Book */
#ifdef DEVRANDOM
	fd = open(DEVRANDOM, O_RDONLY, 0);
	if (fd == -1) {
		perror(DEVRANDOM);
		exit(1);
	}
	read(fd, &i, sizeof(int));
	j = j ^ i;
	close(fd);
#endif
	srand(j);
}

void
shuffle(char *v[], int n)
{
	int i, j;
	char *s;

	for (i = n-1; i > 0; i--) {
		j = ((double)rand() / RAND_MAX) * (i+1);
		s = v[j];
		v[j] = v[i];
		v[i] = s;
	}
}

int
main(int argc, char *argv[])
{
	int i, size, nflag, oneflag;

	nflag = oneflag = 0;
	if (*++argv && !strcmp(*argv, "-n")) {
		argv++;
		argc--;
		nflag = 1;
	}
	if (*argv && !strcmp(*argv, "-1")) {
		argv++;
		argc--;
		oneflag = 1;
	}
	size = argc - 1;

	seed();
	shuffle(argv, size);

	for (i=0; i < size; i++) {
		fputs(argv[i], stdout);
		if (argv[i+1]) {
			if (oneflag) {
				putchar('\n');
			} else {
				putchar(' ');
			}
		}
	}
	if (!nflag)      
		putchar('\n');

	return 0;
}
